import { useMutation } from "react-relay";
import { useCallback } from "react";
import { ConnectionHandler, RecordSourceSelectorProxy } from "relay-runtime";
import { AddCommentInput } from "./__generated__/useAddCommentMutation.graphql";

const graphql = require("babel-plugin-relay/macro");

///注意！名字保持一致； useAddCommentMutation文件函数名和 graphql--mutation；
const mutation = graphql`
  mutation useAddCommentMutation($input: AddCommentInput!) {
    addComment(input: $input) {
      subject {
        id
      }
      commentEdge {
        __id
        node {
          id
          author {
            login
            avatarUrl
          }
          body
        }
      }
    }
  }
`;



export default function useAddCommentMutation() {
  const [commit] = useMutation(mutation);
  return [
    useCallback(
      (commentText: string, issueId: string) => {
        const input: AddCommentInput = {
          body: commentText,
          subjectId: issueId,
        };

        return commit({
          variables: {
            input
          },
          /**
           * Relay merges data from the mutation result based on each response object's `id` value.
           * In this case, however, we also want to add the new comment to the list of issues: Relay
           * doesn't magically know where addComment.commentEdge should be added into the data graph.
           * So we define an `updater` function to imperatively update thee store.
           */
          updater: (store: RecordSourceSelectorProxy) => {
            //const payload = store.getRootField("removeTodo");
            //if (!payload)   return;
            // Get a reference to the issue
            const issue = store.get(issueId);
            if (issue == null) {
              return;
            }
            // Get the list of comments using the same 'key' value as defined in
            // IssueDetailComments
            const comments = ConnectionHandler.getConnection(
                issue,
                'IssueDetailComments_comments', // See IssueDetailsComments @connection
            );
            if (comments == null) {
              return;
            }
            // Insert the edge at the end of the list
            ConnectionHandler.insertEdgeAfter(
                comments,
                store.getRootField('addComment')!.getLinkedRecord('commentEdge'),
                null, // we can specify a cursor value here to insert the new edge after that  cursor
            );
          },
        });
      },
      [commit]
    )
  ];
}
